<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="旅行社名称/检索码/旅行社编码"
            @keyup.enter="handleQuery"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['sys:dept:add']"
          type="success"
          icon="plus"
          @click="handleOpenDialog()"
        >
          新增
        </el-button>
        <el-button
          v-hasPerm="['sys:dept:delete']"
          type="danger"
          :disabled="selectIds.length === 0"
          icon="delete"
          @click="handleDelete()"
        >
          删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="name"
          label="旅行社名称"
          min-width="200"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="code"
          label="旅行社编号"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="queryCode"
          label="检索码"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="contacts"
          label="联系人"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="mobile"
          label="联系电话"
          min-width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="address"
          label="地址"
          min-width="250"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="remark"
          label="备注"
          min-width="250"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:dept:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.parentId, scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:dept:delete']"
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @closed="handleCloseDialog"
    >
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="旅行社名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入旅行社名称" maxlength="100" show-word-limit/>
        </el-form-item>
        <el-form-item label="旅行社编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入旅行社编号" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-form-item label="检索码" prop="queryCode">
          <el-input v-model="formData.queryCode" placeholder="请输入检索码" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="formData.contacts" placeholder="请输入联系人" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入联系电话" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" maxlength="200" show-word-limit/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" maxlength="200" show-word-limit/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="loading"  @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Dept",
  inheritAttrs: false,
});

import DeptAPI, { DeptVO, DeptForm, DeptQuery } from "@/api/system/dept";

const queryFormRef = ref();
const deptFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<DeptQuery>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const deptList = ref<DeptVO[]>();
const deptOptions = ref<OptionType[]>();
const formData = reactive<DeptForm>({
  status: 1,
  parentId: "0",
  sort: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "上级旅行社不能为空", trigger: "change" }],
  name: [{ required: true, message: "旅行社名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "旅行社编号不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
  queryCode: [{ required: true, message: "检索码不能为空", trigger: "blur" }],
});

// 查询旅行社
function handleQuery() {
  loading.value = true;
  DeptAPI.getList(queryParams).then((data) => {
    deptList.value = data;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开旅行社弹窗
 *
 * @param parentId 父旅行社ID
 * @param deptId 旅行社ID
 */
async function handleOpenDialog(parentId?: string, deptId?: number) {
  // 加载旅行社下拉数据
  const data = await DeptAPI.getOptions();
  deptOptions.value = [
    {
      value: "0",
      label: "顶级旅行社",
      children: data,
    },
  ];

  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改旅行社";
    DeptAPI.getFormData(deptId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增旅行社";
    formData.parentId = parentId || "0";
  }
}

// 提交旅行社表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = formData.id;
      if (deptId) {
        DeptAPI.update(deptId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DeptAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除旅行社
function handleDelete(deptId?: number) {
  const deptIds = [deptId || selectIds.value].join(",");

  if (!deptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "0";
  formData.status = 1;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
:deep(.el-popper) {
  max-width: 300px;
}
</style>
